<template>
  <div class="vaw-avatar-container">
    <a-dropdown trigger="click" size="large" @select="handleSelect">
      <div class="action-wrapper">
        <div class="avatar">
          <a-avatar :size="30">
            <img :src="userStore.avatar" />
          </a-avatar>
        </div>
        <span class="nick-name">
          {{ userStore.userName }}
        </span>
        <icon-caret-down class="tip" />
      </div>
      <template #content>
        <a-doption value="personal-center">
          <template #icon>
            <component is="UserOutlined" />
          </template>
          个人中心
        </a-doption>
        <a-doption value="logout">
          <template #icon>
            <component is="LogoutOutlined" />
          </template>
          退出登录
        </a-doption>

        <a-popover v-if="primaryAccount.admin" position="left" v-model:popup-visible="showPop" :content-style="{ padding: '0 3px' }">
          <a-doption value="checkoutAccount">
            <template #icon>
              <component is="UserGroupOutlined" />
            </template>
            切换账号
          </a-doption>
          <template #content>
            <div style="margin: 10px">
              <a-input v-model="userName" @input="filterList" placeholder="请输入名字搜索"></a-input>
            </div>
            <a-scrollbar style="height: 200px; min-width: 200px; overflow: auto">
              <div class="user-box cursor">
                <div v-if="userList[0]">
                  <div class="user-item" @click="toJump(primaryAccount)">【主账号】{{ primaryAccount.userName }}</div>
                  <div class="user-item" @click="toJump(item)" v-for="item in userList" :key="item.id">{{ item.userName }}</div>
                </div>
                <div v-else>
                  <a-empty></a-empty>
                </div>
              </div>
            </a-scrollbar>
          </template>
        </a-popover>
      </template>
    </a-dropdown>
  </div>
</template>

<script lang="ts">
  import { Message, Modal } from '@arco-design/web-vue'
  import { defineComponent, ref } from 'vue'
  import { IconUser as UserOutlined, IconPoweroff as LogoutOutlined, IconCaretDown as CaretDownOutlined, IconUserGroup as UserGroupOutlined } from '@arco-design/web-vue/es/icon'
  import useUserStore from '@/store/modules/user'
  import { useRouter } from 'vue-router'
  import { getOrganizesUser } from '@/api/system'
  import { loginByUserId } from '@/api/login'
  import { init } from 'echarts/core'
  import { onMounted } from 'vue'

  export default defineComponent({
    name: 'VAWavatar',
    components: { UserOutlined, LogoutOutlined, CaretDownOutlined, UserGroupOutlined },
    setup() {
      let firstLoginUserInfo: any = window.localStorage.getItem('first-login-info')
      let primaryAccount: any = JSON.parse(firstLoginUserInfo)
      const userStore = useUserStore()
      let userList: any = ref([])
      let InitUserList: any = ref([])
      let userName = ref('')
      let showPop = ref(false)
      const options = [
        {
          label: '个人中心',
          key: 'personal-center',
          icon: 'UserOutlined',
        },
        {
          label: '退出登录',
          key: 'logout',
          icon: 'LogoutOutlined',
        },
        {
          label: '切换账号',
          key: 'checkoutAccount',
          icon: 'UserGroupOutlined',
        },
      ]
      const router = useRouter()
      function personalCenter() {
        router.push('/system/user/personInfo')
      }

      function logout() {
        Modal.confirm({
          title: '提示',
          content: '是否要退出当前账号？',
          okText: '退出',
          cancelText: '再想想',
          onOk: () => {
            userStore.logout().then(() => {
              window.location.reload()
            })
          },
        })
      }
      function handleSelect(key: string) {
        console.log(key)
        switch (key) {
          case 'personal-center':
            personalCenter()
            break
          case 'logout':
            logout()
            break
        }
      }

      async function getUserList() {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        let id = userStore.userId
        // console.log(userStore.userId)
        const res: any = await getOrganizesUser(params)
        let arr = res?.data?.records || []
        userList.value = arr.filter((e: any) => e.id != id)
        InitUserList.value = arr.filter((e: any) => e.id != id)
      }

      const toJump = async (info: any) => {
        let params = {
          companyId: info.companyId,
          userId: info.id,
        }
        const rs: any = await loginByUserId(params)
        if (rs?.data?.token) {
          localStorage.removeItem('user-info')
          localStorage.removeItem('visited-routes')
          let saasSessionStr = encodeURIComponent(JSON.stringify(rs.data))
          let url = 'https://saas.selleroa.com/#/loginFromErp?' + saasSessionStr
          // let url = 'http://localhost:5080/#/loginFromErp?' + saasSessionStr
          window.location.replace(url)
          window.location.reload()
          return
        }
        Message.error('可能出错了，跳不了了!')
      }

      const filterList = () => {
        userList.value = InitUserList.value.filter((e: any) => {
          return e.userName.includes(userName.value)
        })
      }

      onMounted(async () => {
        await getUserList()
      })

      return {
        userStore,
        options,
        handleSelect,
        userList,
        toJump,
        userName,
        filterList,
        showPop,
        primaryAccount,
      }
    },
  })
</script>

<style lang="less" scoped>
  .user-box {
    width: 200px;
    max-height: 400px;
  }

  .vaw-avatar-container {
    .action-wrapper {
      display: flex;
      align-items: center;
      .avatar {
        display: flex;
        align-items: center;
        & > img {
          border: 1px solid #f6f6f6;
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 50%;
        }
      }
      .nick-name {
        margin: 0 5px;
        .tip {
          transform: rotate(0);
          transition: transform @transitionTime;
          margin-left: 2px;
        }
      }
    }
  }
  .vaw-avatar-container:hover {
    cursor: pointer;
    color: var(--primary-color);
    .tip {
      transform: rotate(180deg);
      transition: transform @transitionTime;
    }
  }

  .user-item {
    height: 30px;
    line-height: 30px;
    padding-left: 5px;
    &:hover {
      background-color: #f6f6f6;
    }
  }
</style>
